<template>
  <div class="app-container">
    <h2 style="margin-bottom: 50px; font-weight:500; font-size: 32px; color: black;">补贴发放</h2>
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="90px" label-position="left">
      <el-row>
        <el-col :span="12">
          <el-form-item label="补贴类型:" prop="exportType">
            <el-select class="typeDiv" v-model="queryParams.exportType" @change="selectType" size="small"
              :style="{ width: '100%' }">
              <el-option v-for="item in subsidyOptions" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size="medium" style="float:right;margin:0;padding-right: 10px;">
            <el-button :loading="buttonLoading" type="primary" @click="submitPending" v-show="!isAdmin"
              v-hasPermi="['agriculture:sub:subpend']">一键处理</el-button>
          </el-form-item>
          <el-form-item size="medium" style="float:right;margin:0;padding-right: 10px;">
            <el-button :loading="buttonLoading" type="primary" @click="submitAll"
              v-hasPermi="['agriculture:sub:submitAll']">一键处理</el-button>
          </el-form-item>
          <el-form-item size="medium" style="float: right;margin:0;padding-right: 10px;">
            <el-button v-if="showYumiColumns || showDadouColumns || showDaoguColumns" :loading="buttonLoading"
              type="primary" @click="geTownSub" v-hasPermi="['agriculture:sub:geTownSub']">生成生产者资金请示文件</el-button>
          </el-form-item>

          <el-form-item size="medium" style="float: right;margin:0;padding-right: 10px;">
            <el-button v-if="showGaodanColumns" :loading="buttonLoading" type="primary" @click="geTownDanSub"
              v-hasPermi="['agriculture:sub:geTownSub']">生成高蛋白大豆资金请示文件</el-button>
          </el-form-item>
          <el-form-item size="medium" style="float: right;margin:0;padding-right: 10px;">
            <el-button v-if="showGaoyouColumns" :loading="buttonLoading" type="primary" @click="geTownYouSub"
              v-hasPermi="['agriculture:sub:geTownSub']">生成高油大豆资金请示文件</el-button>
          </el-form-item>
          <el-form-item size="medium" style="float: right;margin:0;padding-right: 10px;">
            <el-button v-if="showFarmColumns" :loading="buttonLoading" type="primary" @click="geTownFarmSub"
              v-hasPermi="['agriculture:sub:geTownSub']">生成耕地地力资金请示文件</el-button>
          </el-form-item>
          <el-form-item size="medium" style="float: right;margin:0;padding-right: 10px;">
            <el-button v-if="showCropFarmColumns" :loading="buttonLoading" type="primary" @click="geTownCropFarmSub"
              v-hasPermi="['agriculture:sub:geTownSub']">生成耕地轮作资金请示文件</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="身份证号码:" prop="idCard" style="margin:0">
            <el-input v-model="queryParams.idCard" placeholder="请输入身份证号码" clearable size="small" :style="{ width: '90%' }"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="一卡通号码:" prop="bankCard" style="margin:0">
            <el-input v-model="queryParams.bankCard" placeholder="请输入一卡通号码" clearable size="small"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery()">重置</el-button>
          </el-form-item>
        </el-col>

        <!-- 区筛选 -->
        <el-col :span="3" v-hasPermi="['agriculture:process:siftTown']" style="float:right;margin:0">
          <el-form-item prop="villageName" label-width="0px" style="float:right;margin:0">
            <el-select placeholder="全部村" v-model="queryParams.villageName" @change="handleQuery" size="small" clearable
              :style="{ width: '100%' }">
              <el-option v-for="item in villageOptions" :key="item.label" :label="item.label" :value="item.label">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5" v-hasPermi="['agriculture:process:siftTown']" style="float:right;margin:0">
          <el-form-item prop="townName" label-width="30px" style="float:right;margin:0">
            <el-select placeholder="全部乡" v-model="queryParams.townName" @change="handleQueryTown" clearable
              :style="{ width: '100%' }" size="small">
              <el-option v-for="item in townOptions" :key="item.label" :label="item.label" :value="item.label">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 乡筛选 -->
        <el-col :span="4" style="float:right;margin:0">
          <el-form-item prop="villageName" label-width="20px" style="float:right;margin:0"
            v-hasPermi="['agriculture:subsidy:siftVillage']">
            <el-select placeholder="全部村" v-show="!isAdmin" v-model="queryParams.villageName" @change="handleQuery"
              size="small" clearable :style="{ width: '100%' }">
              <el-option v-for="item in villageOptions" :key="item.label" :label="item.label" :value="item.label">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="5" style="color:#0F40F5;font-size: 20px;" v-hasPermi="['agriculture:subsidy:disSum']">
          <el-form-item prop="straName" label-width="20px">
            <!-- 区总面积 -->
            <span v-if="showYumiColumns">{{ queryParams.straName }}总补贴金额：{{ sumData.yubyqutotalPri }}元</span>
            <span v-if="showDadouColumns">{{ queryParams.straName }}总补贴金额：{{ sumData.dadoubyqutotalPri }}元</span>
            <span v-if="showDaoguColumns">{{ queryParams.straName }}总补贴金额：{{ sumData.gubyqutotalPri }}元</span>
            <span v-if="showGaodanColumns">{{ queryParams.straName }}总补贴金额：{{ sumData.youdouGaodanbaibyqutotalPri
            }}元</span>
            <span v-if="showGaoyouColumns">{{ queryParams.straName }}总补贴金额：{{ sumData.youdouGaoyoubyqutotalPri }}元</span>
            <span v-if="showFarmColumns">{{ queryParams.straName }}总补贴金额：{{ sumData.farmlandbyqutotalPri }}元</span>
            <span v-if="showCropFarmColumns">{{ queryParams.straName }}总补贴金额：{{ sumData.cropallprebyqu
            }}元</span>
          </el-form-item>
        </el-col>
        <el-col :span="5" style="color:#0F40F5;font-size: 20px;" v-hasPermi="['agriculture:subsidy:townSum']">
          <el-form-item prop="townName" label-width="20px" v-if="queryParams.townName">
            <span v-if="showYumiColumns">{{ queryParams.townName }}总补贴金额：{{ sumData.yubyxitotalPri }}元</span>
            <span v-if="showDadouColumns">{{ queryParams.townName }}总补贴金额：{{ sumData.dadoubyxitotalPri }}元</span>
            <span v-if="showDaoguColumns">{{ queryParams.townName }}总补贴金额：{{ sumData.gubyxitotalPri }}元</span>
            <span v-if="showGaodanColumns">{{ queryParams.townName }}总补贴金额：{{ sumData.youdouGaodanbaibyxitotalPri
            }}元</span>
            <span v-if="showGaoyouColumns">{{ queryParams.townName }}总补贴金额：{{ sumData.youdouGaoyoubyxitotalPri }}元</span>
            <span v-if="showFarmColumns">{{ queryParams.townName }}总补贴金额：{{ sumData.farmlandbyxitotalPri }}元</span>
            <span v-if="showCropFarmColumns">{{ queryParams.townName }}总补贴金额：{{ sumData.cropallprebyxi
            }}元</span>
          </el-form-item>
        </el-col>
        <el-col :span="5" style="color:#0F40F5;font-size: 20px;" v-hasPermi="['agriculture:subsidy:villSum']">
          <el-form-item prop="villageName" label-width="20px" v-if="queryParams.villageName">
            <span v-if="showYumiColumns">{{ queryParams.villageName }}总补贴金额：{{ sumData.yubycuntotalPri }}元</span>
            <span v-if="showDadouColumns">{{ queryParams.villageName }}总补贴金额：{{ sumData.dadoubycuntotalPri }}元</span>
            <span v-if="showDaoguColumns">{{ queryParams.villageName }}总补贴金额：{{ sumData.gubycuntotalPri }}元</span>
            <span v-if="showGaodanColumns">{{ queryParams.villageName }}总补贴金额：{{ sumData.youdouGaodanbaibycuntotalPri
            }}元</span>
            <span v-if="showGaoyouColumns">{{ queryParams.villageName }}总补贴金额：{{ sumData.youdouGaoyoubycuntotalPri
            }}元</span>
            <span v-if="showFarmColumns">{{ queryParams.villageName }}总补贴金额：{{ sumData.farmlandbycuntotalPri
            }}元</span>
            <span v-if="showCropFarmColumns">{{ queryParams.villageName }}总补贴金额：{{ sumData.cropallprebycun
            }}元</span>
          </el-form-item>
        </el-col>
        <el-col :span="3"><el-form-item /></el-col>

        <el-col :span="3" style="float:right;margin:0">
          <el-form-item style="float:right;margin:0">
            <el-button v-if="true" :loading="buttonLoading" type="success" size="medium"
              @click="handleExport">导出Excel</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="3" style="float:right;">
          <el-form-item>
            <el-button v-if="true" :loading="buttonLoading" type="primary" size="medium" @click="viewTownSub"
              v-hasPermi="['agriculture:sub:viewTownSub']">查看资金请示文件</el-button>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>

    <el-table v-loading="loading" :data="subsidyApplicationList" border fit>
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column type="index" width="60" label="序号" align="center" key="1" />
      <!-- <el-table-column label="工单编号" align="center" prop="appNum" v-if="true"/> -->
      <el-table-column label="申请人" align="center" prop="appyBy" width="80" key="2" />
      <el-table-column label="身份证号码" align="center" prop="idCard" key="3" />
      <el-table-column label="一卡通号码" align="center" prop="bankCard" key="4" />
      <el-table-column label="手机号码" align="center" prop="phone" key="5" />
      <el-table-column label="乡" align="center" prop="townName" key="6" />
      <el-table-column label="村" align="center" prop="villageName" key="7" />

      <template v-if="showYumiColumns">
        <!-- <el-table-column label="玉米补贴面积(亩)" align="center" prop="yumiareaAmount" key="8" /> -->

        <el-table-column label="玉米补贴面积(亩)" align="center" key="8">
          <template #default="scope">
            <el-input v-model="scope.row.yumiareaAmount" @change="value => {
              const num = Number(value);
              if (isNaN(num) || num < 0) {
                this.$message.error('请输入有效的正数');
                scope.row.yumiareaAmount = 0;
                return;
              }
              handleAreaChange(scope.row);
            }" />
          </template>
        </el-table-column>

        <el-table-column label="玉米补贴标准(元/亩)" align="center" key="9">
          <template #default="scope">
            {{ prcieForm.yumi || '—' }}
          </template>
        </el-table-column>
        <el-table-column label="玉米补贴金额(元)" align="center" prop="yumiareaAmountPri" key="10" />
      </template>

      <template v-if="showDadouColumns">
        <!-- <el-table-column label="大豆补贴面积(亩)" align="center" prop="dadouareaAmount" width="100" key="11" /> -->

        <el-table-column label="大豆补贴面积(亩)" align="center" key="11">
          <template #default="scope">
            <el-input v-model="scope.row.dadouareaAmount" @change="value => {
              const num = Number(value);
              if (isNaN(num) || num < 0) {
                this.$message.error('请输入有效的正数');
                scope.row.dadouareaAmount = 0;
                return;
              }
              handleAreaChange(scope.row);
            }" />
          </template>
        </el-table-column>

        <el-table-column label="大豆补贴标准(元/亩)" align="center" width="100" key="12">
          <template #default="scope">
            {{ prcieForm.dadou || '—' }}
          </template>
        </el-table-column>
        <el-table-column label="大豆补贴金额(元)" align="center" prop="dadouareaAmountPri" width="110" key="13" />
      </template>

      <template v-if="showDaoguColumns">
        <!-- <el-table-column label="稻谷补贴面积(亩)" align="center" prop="daoguheareaAmount" width="80" key="14" /> -->
        <el-table-column label="稻谷补贴面积(亩)" align="center" key="14">
          <template #default="scope">
            <el-input v-model="scope.row.daoguheareaAmount" @change="value => {
              const num = Number(value);
              if (isNaN(num) || num < 0) {
                this.$message.error('请输入有效的正数');
                scope.row.daoguheareaAmount = 0;
                return;
              }
              handleAreaChange(scope.row);
            }" />
          </template>
        </el-table-column>
        <el-table-column label="稻谷补贴金额(元)" align="center" prop="daoguheareaAmountPri" key="15" />
        <!-- <el-table-column label="地表水(亩)" align="center" prop="daogudibiareaAmount" width="70" key="16" /> -->
        <el-table-column label="地表水(亩)" align="center" key="16">
          <template #default="scope">
            <el-input v-model="scope.row.daogudibiareaAmount" @change="value => {
              const num = Number(value);
              if (isNaN(num) || num < 0) {
                this.$message.error('请输入有效的正数');
                scope.row.daogudibiareaAmount = 0;
                return;
              }
              handleAreaChange(scope.row);
            }" />
          </template>
        </el-table-column>
        <el-table-column label="地表水补贴标准(元/亩)" align="center" width="80" key="17">
          <template #default="scope">
            {{ prcieForm.daogudibiao || '—' }}
          </template>
        </el-table-column>
        <el-table-column label="地表水补贴金额(元)" align="center" prop="daogudibiareaAmountPri" width="80" key="18" />
        <!-- <el-table-column label="地下水(亩)" align="center" prop="daogudixiaareaAmount" width="70" key="19" /> -->
        <el-table-column label="地下水(亩)" align="center" key="19">
          <template #default="scope">
            <el-input v-model="scope.row.daogudixiaareaAmount" @change="value => {
              const num = Number(value);
              if (isNaN(num) || num < 0) {
                this.$message.error('请输入有效的正数');
                scope.row.daogudixiaareaAmount = 0;
                return;
              }
              handleAreaChange(scope.row);
            }" />
          </template>
        </el-table-column>

        <el-table-column label="地下水补贴标准(元/亩)" align="center" width="80" key="20">
          <template #default="scope">
            {{ prcieForm.daogudixia || '—' }}
          </template>
        </el-table-column>
        <el-table-column label="地下水补贴金额(元)" align="center" prop="daogudixiaareaAmountPri" width="80" key="21" />
      </template>

      <template v-if="showFarmColumns">
        <el-table-column label="耕地地力补贴面积(亩)" align="center" key="22">
          <template #default="scope">
            <el-input v-model="scope.row.farmlandareaAmount" @change="value => {
              const num = Number(value);
              if (isNaN(num) || num < 0) {
                this.$message.error('请输入有效的正数');
                scope.row.farmlandareaAmount = 0;
                return;
              }
              handleAreaChange(scope.row);
            }" />
          </template>
        </el-table-column>
        <el-table-column label="耕地地力补贴标准(元/亩)" align="center" width="100" key="23">
          <template #default="scope">
            {{ prcieForm.farmland || '—' }}
          </template>
        </el-table-column>
        <el-table-column label="耕地地力补贴金额(元)" align="center" prop="farmlandareaAmountPri" width="110" key="24" />
      </template>

      <template v-if="showCropFarmColumns">
        <el-table-column label="耕地轮作补贴面积(亩)" align="center" key="22">
          <template #default="scope">
            <el-input v-model="scope.row.cropall" @change="value => {
              const num = Number(value);
              if (isNaN(num) || num < 0) {
                this.$message.error('请输入有效的正数');
                scope.row.cropall = 0;
                return;
              }
              handleAreaChange(scope.row);
            }" />
          </template>
        </el-table-column>
        <el-table-column label="耕地轮作补贴标准(元/亩)" align="center" width="100" key="23">
          <template #default="scope">
            {{ prcieForm.cropfarmland || '—' }}
          </template>
        </el-table-column>
        <el-table-column label="耕地轮作补贴金额(元)" align="center" prop="cropallpre" width="110" key="24" />
      </template>

      <template v-if="showGaodanColumns">
        <!-- <el-table-column label="高蛋白大豆补贴面积(亩)" align="center" prop="areaAmountdouGaodanbai" width="150" key="25" /> -->
        <el-table-column label="高蛋白大豆补贴面积(亩)" align="center" key="25">
          <template #default="scope">
            <el-input v-model="scope.row.areaAmountdouGaodanbai" @change="value => {
              const num = Number(value);
              if (isNaN(num) || num < 0) {
                this.$message.error('请输入有效的正数');
                scope.row.areaAmountdouGaodanbai = 0;
                return;
              }
              handleAreaChange(scope.row);
            }" />
          </template>
        </el-table-column>
        <el-table-column label="高蛋白大豆补贴标准(元/亩)" align="center" width="100" key="26">
          <template #default="scope">
            {{ prcieForm.gaodanbaidadou || '—' }}
          </template>
        </el-table-column>
        <el-table-column label="高蛋白大豆补贴金额(元)" align="center" prop="areaAmountdouGaodanbaiPri" width="110" key="27" />
      </template>

      <template v-if="showGaoyouColumns">
        <!-- <el-table-column label="高油大豆补贴面积(亩)" align="center" prop="areaAmountdouGaoyou" width="100" key="28" /> -->
        <el-table-column label="高油大豆补贴面积(亩)" align="center" key="28">
          <template #default="scope">
            <el-input v-model="scope.row.areaAmountdouGaoyou" @change="value => {
              const num = Number(value);
              if (isNaN(num) || num < 0) {
                this.$message.error('请输入有效的正数');
                scope.row.areaAmountdouGaoyou = 0;
                return;
              }
              handleAreaChange(scope.row);
            }" />
          </template>
        </el-table-column>
        <el-table-column label="高油大豆补贴标准(元/亩)" align="center" width="100" key="29">
          <template #default="scope">
            {{ prcieForm.gaoyoudadou || '—' }}
          </template>
        </el-table-column>
        <el-table-column label="高蛋白大豆补贴金额(元)" align="center" prop="areaAmountdouGaoyouPri" width="100" key="30" />
      </template>

      <!-- <el-table-column label="当前流程" align="center" prop="nodeName" width="120" key="21" /> -->
      <el-table-column label="状态" align="center" prop="statusShow" width="70" key="31" />
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

  </div>
</template>
<script>
import { queryTownRes, getPrice, listProduce, updateProduce, submitSub, getProduceById, getProduceByappNum, submitProduce, rejectAllProduce, rejectProduce, approveProduce } from "@/api/agriculture/agriculture";
import { listStrativeArea, getStrativeArea, delStrativeArea, addStrativeArea, updateStrativeArea } from "@/api/subsidy/strativeArea";
import { debounce } from 'lodash'
export default {
  components: {},
  data() {
    const now = new Date();
    return {

      pdfUrl: '',
      //补贴标准
      prcieForm: {
        yumi: undefined,
        dadou: undefined,
        // daogu: undefined,
        daogudibiao: undefined,
        daogudixia: undefined,
        farmland: undefined,
        cropfarmland: undefined,
        gaodanbaidadou: undefined,
        gaoyoudadou: undefined
      },

      year: now.getFullYear(),
      curyear: now.getFullYear() - 1,
      sumData: [],


      subsidyOptions: [{
        "label": "玉米补贴",
        "value": "玉米补贴"
      }, {
        "label": "大豆补贴",
        "value": "大豆补贴"
      }, {
        "label": "稻谷补贴",
        "value": "稻谷补贴"
      }, {
        "label": "高油大豆补贴",
        "value": "高油大豆补贴"
      }, {
        "label": "高蛋白大豆补贴",
        "value": "高蛋白大豆补贴"
      }, {
        "label": "耕地地力补贴",
        "value": "耕地地力补贴"
      }, {
        "label": "耕地轮作补贴",
        "value": "耕地轮作补贴"
      }],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      isAdmin: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 补贴申请表格数据
      subsidyApplicationList: [],
      townOptions: [],
      villageOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        appType: '生产者补贴',
        idCard: undefined,
        bankCard: undefined,
        straName: '滴道区',
        villageName: undefined,
        townName: undefined,
        isprice: '2',
        exportType: '玉米补贴',
        year: now.getFullYear(),
      },
    };
  },

  computed: {
    //补贴数据展示
    showYumiColumns() {
      return this.queryParams.exportType === '玉米补贴';
    },
    showDadouColumns() {
      return this.queryParams.exportType === '大豆补贴';
    },
    showDaoguColumns() {
      return this.queryParams.exportType === '稻谷补贴';
    },
    showGaodanColumns() {
      return this.queryParams.exportType === '高蛋白大豆补贴';
    },
    showGaoyouColumns() {
      return this.queryParams.exportType === '高油大豆补贴';
    },
    showFarmColumns() {
      return this.queryParams.exportType === '耕地地力补贴';
    },
    showCropFarmColumns() {
      return this.queryParams.exportType === '耕地轮作补贴';
    }
  },
  watch: {},
  created() {
    this.role = this.$store.state.user.roles[0];
    // console.log("当前登录角色", this.role)

    if (this.$store.state.user.user.villageName) {
      this.queryParams.villageName = this.$store.state.user.user.villageName;
    }
    if (this.role == 'admin') {
      this.isAdmin = true;
    }

    if (this.role == 'town') {
      this.townName = this.$store.state.user.user.townName;
      this.queryParams.townName = this.townName
      console.log("当前登录角色乡名字", this.townName)
      listStrativeArea({ townName: this.townName }).then(response => {
        console.log("村列表数据展示", response[0].children[0].children)
        this.villageOptions = response[0].children[0].children;
        // if (this.villageOptions.length > 0) {
        //   this.queryParams.villageName = this.villageOptions[0].label; // 或 .value，看你要绑定哪个
        //   // 触发后续查询（可选）
        //   this.handleQuery(); // 如果你想在默认选中后立即查询
        // }
      })
    }

    if (this.role == 'district' || this.role == 'admin') {
      this.straName = '滴道区'
      this.queryParams.straName = this.straName
      listStrativeArea({ departmentName: '滴道区' }).then(response => {
        this.townOptions = response[0]?.children?.filter(item => item.type === 'town') || [];

        // if (this.townOptions.length > 0) {
        //   this.queryParams.townName = this.townOptions[0].label; // 或 .value，看你要绑定哪个
        //   this.updateVillageOptions()

        //   this.handleQuery(); // 如果你想在默认选中后立即查询
        // }
        // console.log("乡列表数据展示", response[0].children)
        // this.townOptions = response[0].children;
      })
    }

    this.getList();

  },
  mounted() {
    this.fetchPriceData();
  },
  methods: {
    handleAreaChange: debounce(function (row) {
      const postData = { ...row }; // 完整数据
      this.loading = true;
      updateProduce(postData)
        .then(response => {
          this.getList();
          this.$modal.msgSuccess("修改成功");

        })
        .catch(() => {
          this.$modal.msgError("修改失败，请重试");
        })
        .finally(() => {
          this.getList();
          this.loading = false;
        });
    }, 500), // 500ms 防抖
    fetchPriceData() {
      getPrice({ year: this.year })
        .then(res => {
          const data = res || [];
          console.log("补贴金额", data);

          const mapping = {
            '玉米补贴': 'yumi',
            '大豆补贴': 'dadou',
            // '稻谷补贴': 'daogu',
            '稻谷地表水补贴': 'daogudibiao',
            '稻谷地下水补贴': 'daogudixia',
            '高油大豆补贴': 'gaoyoudadou',
            '高蛋白大豆补贴': 'gaodanbaidadou',
            '耕地地力补贴': 'farmland',
            '耕地轮作补贴': 'cropfarmland'
          };

          data.forEach(item => {
            const field = mapping[item.type];
            console.log("补贴字段", field);
            if (field) {
              // 填充值（注意：price 可能是字符串）
              this.prcieForm[field] = Number(item.price);
            }
          });
        })
        .catch(err => {
          this.$message.error('获取补贴数据失败：' + (err.message || '网络错误'));
          this.initSubmitStates(); // 出错时仍允许编辑
        });
    },


    updateVillageOptions() {
      // 清空当前村庄选择
      this.queryParams.villageName = '';

      if (!this.queryParams.townName) {
        this.villageOptions = [];
        return;
      }

      // 从 townOptions 中找到选中的乡镇
      const selectedTown = this.townOptions.find(town => town.label === this.queryParams.townName);

      // 设置村庄选项为其 children
      this.villageOptions = selectedTown?.children || [];
      // 如果有村庄，自动选中第一个
      if (this.villageOptions.length > 0) {
        this.queryParams.villageName = this.villageOptions[0].label; // 或 .value，看你要绑定哪个
        // 触发后续查询（可选）
        this.handleQuery(); // 如果你想在默认选中后立即查询
      }
    },

    // 当乡镇选择变化时触发
    handleQueryTown() {
      console.log("当前搜索条件", this.queryParams)
      this.handleQuery();
      this.updateVillageOptions();

      // 其他查询逻辑（如提交表单、刷新列表等）
    },
    //村级一键提交补贴发放



    submitPending() {

      console.log("this.queryParams.appType", this.queryParams.appType, this.year)
      this.$confirm(`此操作将提交${this.queryParams.appType}补贴到下一流程节点`, '提交补贴提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        submitSub({ year: this.year, appType: this.queryParams.appType, isprice: '2' }).then(() => {
          this.$modal.msgSuccess("提交成功")
        })
      }).catch(error => {
        this.$message({ type: 'error', message: '提交失败' })
      })


    },
    //区级一键提交补贴发放
    submitAll() {
      console.log("this.queryParams.appType", this.queryParams.appType, this.year)
      submitSub({ year: this.year, appType: this.queryParams.appType, isprice: "2" }).then(response => {
        this.$modal.msgSuccess("提交成功");
        this.getList();
      }).catch(error => {
        this.$message({ type: 'error', message: '提交失败!' });
      });
    },

    geTownSub() {   //生产者补贴乡级资金
      this.$router.push('/agricultureSubsidy/townSub')
    },
    geTownFarmSub() {   //耕地地力补贴乡级资金
      this.$router.push('/agricultureSubsidy/townFarmSub')
    },
    geTownCropFarmSub() {   //耕地地力补贴乡级资金
      this.$router.push('/agricultureSubsidy/townCropFarmSub')
    },
    geTownDanSub() { //生成大豆高油高蛋白大豆乡级资金请示文件
      this.$router.push({
        path: '/agricultureSubsidy/townDouSub',
        query: {
          checkType: '高蛋白大豆补贴'
        }
      })
    },
    geTownYouSub() { //生成大豆高油高蛋白大豆乡级资金请示文件
      this.$router.push({
        path: '/agricultureSubsidy/townDouSub',
        query: {
          checkType: '高油大豆补贴'
        }
      })
    },
    viewTownSub() {
      if (this.queryParams.townName) {
        console.log("查看的类型", this.queryParams.appType)
        queryTownRes({ year: this.year, type: this.queryParams.appType, name: this.queryParams.townName, isprice: '2' }).then(res => {
          if (res.rows.length > 0 && res.rows[res.rows.length - 1].hechafile) {
            console.log("res", res.rows[res.rows.length - 1].hechafile)
            const pdfUrl = res.rows[res.rows.length - 1].hechafile.replace('172.24.254.135', '111.40.188.220');
            // this.$router.push({ name: 'PdfViewer', query: { url: pdfUrl } })
            const routeData = this.$router.resolve({
              name: 'PdfViewer',
              query: { url: pdfUrl }
            });
            window.open(routeData.href, '_blank');
          } else {
            this.$message({ type: 'error', message: '未提交数据!' });
          }
        })
      } else {
        this.$message({ type: 'error', message: '请选择需要查看资金请示的乡!' });
      }
    },

    // 补贴状态按钮切换
    selectType(value) {
      console.log("选择的类型", value);
      // 定义前三个是“生产者补贴”的类型
      const producerSubsidyTypes = [
        '玉米补贴',
        '大豆补贴',
        '稻谷补贴'
      ];
      // 判断并设置 queryParams.appType
      if (producerSubsidyTypes.includes(value)) {
        this.queryParams.appType = '生产者补贴';
      } else {
        this.queryParams.appType = value; // 高油大豆补贴、高蛋白大豆补贴等保持原值
      }
      this.handleQuery(); // 触发查询
    },
    /** 查询补贴申请列表 */
    getList() {
      this.subsidyApplicationList = [];
      this.loading = true;
      console.log("queryParams", this.queryParams)
      listProduce(this.queryParams).then(response => {
        // console.log("汇总数据", response);
        this.total = response.total;
        this.sumData = response;

        let list = response.rows || [];
        console.log("list", list)
        // 如果是生产者补贴下的细分类型，进行过滤
        // if (this.queryParams.appType === '生产者补贴') {
        //   if (this.queryParams.exportType === '玉米补贴') {
        //     list = list.filter(item => Number(item.yumiareaAmount) > 0);
        //   } else if (this.queryParams.exportType === '大豆补贴') {
        //     list = list.filter(item => Number(item.dadouareaAmount) > 0);
        //   } else if (this.queryParams.exportType === '稻谷补贴') {
        //     list = list.filter(item => Number(item.daoguheareaAmount) > 0);
        //   }
        // }
        // 其他类型（如高油/高蛋白）不需要过滤，直接显示
        this.subsidyApplicationList = list;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 导出按钮操作 */
    handleExport() {
      console.log("导出excel的查询信息", this.queryParams)

      this.download('/subsidy/subsidyApplicationPlanting/export', {
        ...this.queryParams
      }, `subsidyApplication_${new Date().getTime()}.xlsx`)
    },

  }
}

</script>
<style scoped>
.app-container {
  background-color: white !important;
}

.el-row {
  margin-bottom: 5px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-select {
  .el-input__inner {
    width: 140px;
  }
}

.typeDiv {
  .el-input__inner {
    width: 185px;
  }
}

.el-scrollbar {
  height: 200px;
}

.pdf-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 600px;
  height: 900px;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.pdf-dialog-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  max-width: 90%;
  max-height: 90%;
  overflow: auto;
  position: relative;
}

.close {
  position: absolute;
  top: 10px;
  right: 15px;
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
}
</style>
  
  
